package com.kkd.kkdapp.activity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.adapter.CalendarCurdayAdapter;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.CalendarData;
import com.kkd.kkdapp.http.entity.CalendarListData;
import com.kkd.kkdapp.http.entity.CalendarListDataItem;
import com.kkd.kkdapp.http.entity.CalendarMonthItem;
import com.kkd.kkdapp.http.entity.IncomeByDaysItem;
import com.kkd.kkdapp.http.entity.MonthTabsItem;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.view.CategoryTabStrip;
import com.kkd.kkdapp.view.KCalendar;
import com.kkd.kkdapp.view.KCalendar.OnCalendarClickListener;
import com.kkd.kkdapp.view.KCalendar.OnCalendarDateChangedListener;
import com.kkd.kkdapp.view.RepaymentHistoryView;

public class CalendarActivity extends BaseActivity {

	private Context mContext = this;

	private static final int SUC_REQUEST = 1001;
	private static final int FAIL_REQUEST = 1002;
	private static final int SUC_CURDAY = 1003;
	private static final int FAIL_CURDAY = 1004;
	private Date thisday;// 今天
	private View back;
	private TextView tv_title;
	private View history;
	private CategoryTabStrip tabs;
	private KCalendar mKCalendar;
	List<MonthTabsItem> list_year_month = new ArrayList<MonthTabsItem>();// 存储年月
	String date = "";// 设置默认选中的日期 格式为 “2014-04-05” 标准DATE格式
	private boolean isInCalendarView = true;// 当前展示的view是否为日历view
	private View calendarView;
	private RepaymentHistoryView historyView;
	private ListView mListView_curDay;
	private ImageView iv_right;
	private TextView tv_geted;
	private TextView tv_get_wait;
	private View loading_curDay;
	private ObjectAnimator animation_toHistory;
	private ObjectAnimator lscale_toHistory;
	private ObjectAnimator animation_toCalendar;
	private ObjectAnimator lscale_toCalendar;
	private String title_calendar = "";// 日历view可见时的页面标题
	private CalendarCurdayAdapter mAdapter;
	private DecimalFormat df_point2 = new DecimalFormat("###,##0.00");
	private List<CalendarListDataItem> dataList_curDay = new ArrayList<CalendarListDataItem>();// 放置具体到每一天的列表的数据源
	private int curPositionOfMonthTabs = 0;// 当前月份在list中的position
	private View parent_mKCalendar;
	private Dialog loadDialog;

	private Handler mHandler = new Handler() {
		@SuppressWarnings("deprecation")
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case SUC_REQUEST:
				if (loadDialog != null) {
					loadDialog.cancel();
					loadDialog = null;
				}
				CalendarData calendarData = (CalendarData) msg.obj;
				List<CalendarMonthItem> monthList = calendarData.getDataList();
				setKcalendarStatus(monthList);
				break;

			case FAIL_REQUEST:
				if (loadDialog != null) {
					loadDialog.cancel();
					loadDialog = null;
				}
				String desc = (String) msg.obj;
				if (!TextUtils.isEmpty(desc)) {
					AppUtil.makeToastForCustomer(mContext, desc);
				}
				break;

			case SUC_CURDAY:
				loading_curDay.setVisibility(View.GONE);
				CalendarListData calendarListData = (CalendarListData) msg.obj;
				if (calendarListData != null) {
					List<CalendarListDataItem> curDayItems = calendarListData
							.getData();
					if (curDayItems != null && curDayItems.size() > 0) {
						// 请求接口时所传的日期
						String date_request = curDayItems.get(0)
								.getBillDateDesc();
						// 只有当当前选择的日期与请求接口时传递的参数相同时才添加数据
						if (!TextUtils.isEmpty(date_request)
								&& date_request.equals(date)) {
							dataList_curDay.clear();
							dataList_curDay.addAll(curDayItems);
						}
					}
				}
				mAdapter.notifyDataSetChanged();
				break;

			case FAIL_CURDAY:
				loading_curDay.setVisibility(View.GONE);
				String desc_curday = (String) msg.obj;
				if (!TextUtils.isEmpty(desc_curday)) {
					AppUtil.makeToastForCustomer(mContext, desc_curday);
				}
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calendar);
		thisday = new Date();
		initListMonthOfTabs();
		initView();
		initAnimation();
		initListener();
		requestCalendarData();
	}

	/**
	 * 设置指定月份有tip标记
	 * 
	 * @param list
	 */
	private void setTipTabs(List<Integer> list_haveTip,
			List<CalendarMonthItem> monthList) {
		for (int i = 0; i < list_year_month.size(); i++) {
			list_year_month.get(i).init();
		}

		for (int i = 0; i < list_haveTip.size(); i++) {
			MonthTabsItem item = list_year_month.get(list_haveTip.get(i));
			item.setHaveTip(true);
			item.setPaidMoney(monthList.get(i).getPaidMoney());
			item.setUnpaidMoney(monthList.get(i).getUnpaidMoney());
		}

		tabs.notifyDataSetChanged();
	}

	/**
	 * 初始化日历
	 */
	private void initKCalendar() {
		/*
		 * 设置标题为当前年月
		 */
		title_calendar = "还款日历-" + (thisday.getYear() + 1900);
		tv_title.setText(title_calendar);
		/*
		 * mKCalendar的宽高皆为屏幕宽度
		 */
		LayoutParams params = mKCalendar.getLayoutParams();
		params.width = LayoutParams.MATCH_PARENT;
		params.height = (int) (SystemUtils.getScreenWidth(mContext) * 6.7 / 7);
		mKCalendar.setLayoutParams(params);
		/*
		 * 设置mKCalendar容器的宽高皆为屏幕宽度
		 */
		LayoutParams params_parent = parent_mKCalendar.getLayoutParams();
		params_parent.width = LayoutParams.MATCH_PARENT;
		params_parent.height = (int) (SystemUtils.getScreenWidth(mContext) * 6.7 / 7);
		parent_mKCalendar.setLayoutParams(params_parent);
		mKCalendar.updateCalendarHeight(parent_mKCalendar, params_parent);
		/*
		 * 初始化mKCalendar
		 */
		// 设置KCalendar的父View和父View的参数
		mKCalendar.setParentAndParams(parent_mKCalendar, params_parent);
		// 监听所选中的日期
		mKCalendar.setOnCalendarClickListener(new OnCalendarClickListener() {

			public void onCalendarClick(int row, int col, String dateFormat) {
				int month = Integer.parseInt(dateFormat.substring(
						dateFormat.indexOf("-") + 1,
						dateFormat.lastIndexOf("-")));

				if (mKCalendar.getCalendarMonth() - month == 1// 跨年跳转
						|| mKCalendar.getCalendarMonth() - month == -11) {
					// mKCalendar.lastMonth();
				} else if (month - mKCalendar.getCalendarMonth() == 1 // 跨年跳转
						|| month - mKCalendar.getCalendarMonth() == -11) {
					// mKCalendar.nextMonth();
				} else {
					if (mKCalendar.hasMarked(dateFormat)
							&& !dateFormat.equals(date)) {
						mKCalendar.removeAllBgColorOnly();
						mKCalendar.setCalendarDayBgColor(dateFormat,
								R.drawable.mycalendar_dot);
						date = dateFormat;// 最后返回给全局 date
						requestCurDayList(dateFormat);
					}
				}
			}
		});

		// 监听当前月份
		mKCalendar
				.setOnCalendarDateChangedListener(new OnCalendarDateChangedListener() {
					public void onCalendarDateChanged(int year, int month) {
						date = "";
						mKCalendar.removeAllBgColor();
						clearListview();
						title_calendar = "还款日历-" + year;
						tv_title.setText(title_calendar);
						String mongthString;
						if (Integer.toString(month).length() == 1) {
							mongthString = "0" + month;
						} else {
							mongthString = "" + month;
						}
						int position = 0;
						for (int i = 0; i < list_year_month.size(); i++) {
							if (list_year_month.get(i).getMonthString()
									.equals(year + "-" + mongthString)) {
								position = i;
								break;
							}
						}
						tabs.setCurTabs(position);
						tv_geted.setText(df_point2.format(list_year_month.get(
								position).getPaidMoney() * 0.01));
						tv_get_wait.setText(df_point2.format(list_year_month
								.get(position).getUnpaidMoney() * 0.01));
						curPositionOfMonthTabs = position;
					}
				});
	}

	private void initView() {
		back = findViewById(R.id.condition_img);
		tv_title = (TextView) findViewById(R.id.condition_tv);
		history = findViewById(R.id.history_tv);
		// 右上角图标
		iv_right = (ImageView) findViewById(R.id.iv_right);
		// 日历view
		calendarView = findViewById(R.id.calendarView);
		// 当前选中日listview
		mListView_curDay = (ListView) findViewById(R.id.mListView_curDay);
		mListView_curDay.setDividerHeight(0);
		initHeadView();
		mAdapter = new CalendarCurdayAdapter(mContext, dataList_curDay);
		mListView_curDay.setAdapter(mAdapter);
		// 历史view
		historyView = (RepaymentHistoryView) findViewById(R.id.historyView);
	}

	/**
	 * 初始化日历页面listview的头部view
	 */
	private void initHeadView() {
		View headView_curDay = LayoutInflater.from(mContext).inflate(
				R.layout.headview_calenadr_listview, null);
		// 本月已收金额
		tv_geted = (TextView) headView_curDay.findViewById(R.id.tv_geted);
		// 本月待收金额
		tv_get_wait = (TextView) headView_curDay.findViewById(R.id.tv_get_wait);
		// 请求每日列表时loading标识
		loading_curDay = headView_curDay.findViewById(R.id.loading_curDay);
		// 放置日历的容器
		parent_mKCalendar = headView_curDay
				.findViewById(R.id.parent_mKCalendar);
		// 日历
		mKCalendar = (KCalendar) headView_curDay.findViewById(R.id.mKCalendar);
		// 滑动tab
		tabs = (CategoryTabStrip) headView_curDay
				.findViewById(R.id.category_strip);
		initKCalendar();
		tabs.setKcalendarAndDate(mKCalendar, list_year_month);
		mListView_curDay.addHeaderView(headView_curDay);
	}

	/**
	 * 改变日历控件的状态
	 */
	@SuppressWarnings("deprecation")
	private void setKcalendarStatus(List<CalendarMonthItem> monthList) {
		if (monthList != null && monthList.size() > 0) {
			// 标记有还款的月份
			List<Integer> list_haveTip = new ArrayList<Integer>();
			for (int i = 0; i < list_year_month.size(); i++) {
				if (isInMonthList(list_year_month.get(i).getMonthString(),
						monthList)) {
					list_haveTip.add(i);
				}
			}
			setTipTabs(list_haveTip, monthList);
			// 标记有还款的天
			for (int i = 0; i < monthList.size(); i++) {
				CalendarMonthItem item_month = monthList.get(i);
				List<IncomeByDaysItem> list_day = item_month.getIncomeByDays();
				if (list_day != null) {
					for (int j = 0; j < list_day.size(); j++) {
						IncomeByDaysItem item_day = list_day.get(j);
						String formatDate = KCalendar.format(new Date(
								item_month.getYear() - 1900, item_month
										.getMonthOfYear() - 1, item_day
										.getDayOfMonth()));
						boolean isLixi = (item_day.getExpectedInterest()
								+ item_day.getExpectedExtraInterest() + item_day
								.getExpectedCouponInterest()) > 0;
						boolean isBenjin = item_day.getExpectedPrincipal() > 0;
						if (isLixi && !isBenjin) {// 利息还款
							mKCalendar.addMarkOnly(formatDate,
									KCalendar.POINT_RED);
						} else if (isBenjin && !isLixi) {// 本金还款
							mKCalendar.addMarkOnly(formatDate,
									KCalendar.POINT_BLUE);
						} else if (isLixi && isBenjin) {// 利息，本金还款
							mKCalendar.addMarkOnly(formatDate,
									KCalendar.POINT_RED_BLUE);
						}
					}
				}
			}
			mKCalendar.notifyDataSetChanged();
			// 设置选中月份的本月已收和本月待收
			tv_geted.setText(df_point2.format(list_year_month.get(
					curPositionOfMonthTabs).getPaidMoney() * 0.01));
			tv_get_wait.setText(df_point2.format(list_year_month.get(
					curPositionOfMonthTabs).getUnpaidMoney() * 0.01));
			/*
			 * 如果今天有还款，默认选中
			 */
			if (mKCalendar.hasMarked(KCalendar.format(thisday))) {
				mKCalendar.removeAllBgColorOnly();
				mKCalendar.setCalendarDayBgColor(KCalendar.format(thisday),
						R.drawable.mycalendar_dot);
				date = KCalendar.format(thisday);
				requestCurDayList(date);
			}
		}
	}

	private void initListener() {
		back.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				finish();
			}
		});
		history.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				cancelAnimation();
				if (isInCalendarView) {
					animation_toHistory.start();
				} else {
					animation_toCalendar.start();
				}
				isInCalendarView = !isInCalendarView;
			}
		});
	}

	/**
	 * 初始化切换动画
	 */
	private void initAnimation() {
		animation_toHistory = ObjectAnimator.ofFloat(calendarView, "scaleX",
				1.0F, 0F);
		animation_toHistory.setDuration(250);
		lscale_toHistory = ObjectAnimator.ofFloat(historyView, "scaleX", 0.0F,
				1.0F);
		lscale_toHistory.setDuration(500);
		animation_toHistory.addListener(new AnimatorListener() {

			@Override
			public void onAnimationStart(Animator animation) {

			}

			@Override
			public void onAnimationRepeat(Animator animation) {

			}

			@Override
			public void onAnimationEnd(Animator animation) {
				calendarView.setVisibility(View.GONE);
				historyView.setVisibility(View.VISIBLE);
				lscale_toHistory.start();
				tv_title.setText("还款日程");
				iv_right.setImageResource(R.drawable.icon_right_calendar);
			}

			@Override
			public void onAnimationCancel(Animator animation) {

			}
		});

		animation_toCalendar = ObjectAnimator.ofFloat(historyView, "scaleX",
				1.0F, 0F);
		animation_toCalendar.setDuration(250);
		lscale_toCalendar = ObjectAnimator.ofFloat(calendarView, "scaleX",
				0.0F, 1.0F);
		lscale_toCalendar.setDuration(500);
		animation_toCalendar.addListener(new AnimatorListener() {

			@Override
			public void onAnimationStart(Animator animation) {

			}

			@Override
			public void onAnimationRepeat(Animator animation) {

			}

			@Override
			public void onAnimationEnd(Animator animation) {
				calendarView.setVisibility(View.VISIBLE);
				historyView.setVisibility(View.GONE);
				lscale_toCalendar.start();
				tv_title.setText(title_calendar);
				iv_right.setImageResource(R.drawable.icon_right_list);
			}

			@Override
			public void onAnimationCancel(Animator animation) {

			}
		});
	}

	/**
	 * 取消动画
	 */
	private void cancelAnimation() {
		if (animation_toHistory != null) {
			animation_toHistory.cancel();
		}
		if (lscale_toHistory != null) {
			lscale_toHistory.cancel();
		}
		if (animation_toCalendar != null) {
			animation_toCalendar.cancel();
		}
		if (lscale_toCalendar != null) {
			lscale_toCalendar.cancel();
		}
	}

	/**
	 * 获取下个月的Date
	 * 
	 * @param curDate
	 * @return
	 */
	private Date getNextDate(Date curDate) {
		int curMonth = curDate.getMonth();
		int curYear = curDate.getYear();
		if (curMonth == Calendar.DECEMBER) {
			curYear++;
			curMonth = Calendar.JANUARY;
		} else {
			curMonth++;
		}
		return new Date(curYear, curMonth, 1);
	}

	/**
	 * 初始年月数据源
	 */
	private void initListMonthOfTabs() {
		Date curDate = new Date();
		String curDateString = KCalendar.format(curDate);
		list_year_month.add(new MonthTabsItem(curDateString.substring(0,
				curDateString.lastIndexOf("-")), false, 0, 0));
		for (int i = 0; i < 11; i++) {
			curDate = getNextDate(curDate);
			String newDateString = KCalendar.format(curDate);
			list_year_month.add(new MonthTabsItem(newDateString.substring(0,
					newDateString.lastIndexOf("-")), false, 0, 0));
		}
	}

	/**
	 * 清除listview上的数据
	 */
	private void clearListview() {
		loading_curDay.setVisibility(View.GONE);
		dataList_curDay.clear();
		mAdapter.notifyDataSetChanged();
	}

	/**
	 * 将int型的年和月转为yyyy-MM格式
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	private String getDateString(int year, int month) {
		if (month < 10) {
			return year + "-0" + month;
		} else {
			return year + "-" + month;
		}
	}

	/**
	 * 判断月份是否属于接口返回的月份list
	 * 
	 * @return
	 */
	private boolean isInMonthList(String monthString,
			List<CalendarMonthItem> monthList) {
		for (int i = 0; i < monthList.size(); i++) {
			if (monthString.equals(getDateString(monthList.get(i).getYear(),
					monthList.get(i).getMonthOfYear()))) {
				return true;
			}
		}
		return false;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		cancelAnimation();
		if (mKCalendar != null) {
			mKCalendar.cancelTimerAndTask();
		}
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
	}

	/**
	 * 请求还款日历接口
	 */
	private void requestCalendarData() {
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils.toLoadDialog(mContext, "加载中...");
		KkdHttpMagager.getInstance().getCalendarData(CalendarData.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						Message msg = Message.obtain();
						msg.what = SUC_REQUEST;
						msg.obj = responseBody;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = Message.obtain();
						msg.what = FAIL_REQUEST;
						msg.obj = desc;
						mHandler.sendMessage(msg);
					}
				});
	}

	/**
	 * 请求所点击日期的还款列表
	 */
	@SuppressWarnings("deprecation")
	private void requestCurDayList(String curDay) {
		dataList_curDay.clear();
		mAdapter.notifyDataSetChanged();
		loading_curDay.setVisibility(View.VISIBLE);
		KkdHttpMagager.getInstance().getCalendarListCurday(curDay,
				CalendarListData.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						Message msg = Message.obtain();
						msg.what = SUC_CURDAY;
						msg.obj = responseBody;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = Message.obtain();
						msg.what = FAIL_CURDAY;
						msg.obj = desc;
						mHandler.sendMessage(msg);
					}
				});
	}
}
